from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtSql import *
import Ui_coaEdit

class CoaEdit(QDialog, Ui_coaEdit.Ui_coaEditDlg):
    
  StyleSheet = """
QLineEdit[mandatory="true"] {
    background-color: rgb(255, 255, 127);
    color: darkblue;
}
"""

  def __init__(self, dbConn, tipe,  dataGlob, parent=None):
        super(CoaEdit, self).__init__(parent)
        self.setupUi(self)
        self.db = dbConn
        self.tipe = tipe
        self.dataGlob = dataGlob
        
        self.mastModel = QSqlTableModel(self)
        self.mastModel.setTable("master_kode_perkiraan")
        self.mastModel.setEditStrategy(QSqlTableModel.OnManualSubmit)
        
        self.lineedits = (self.acc_le, self.desc_le)
        for lineEdit in self.lineedits:
            lineEdit.setProperty("mandatory", QVariant(True))
        self.setStyleSheet(CoaEdit.StyleSheet)
        
        self.mapModel = QSqlTableModel(self)
        self.mapModel.setTable("master_kode_map")
        self.mapModel.setEditStrategy(QSqlTableModel.OnManualSubmit)
        self.mapModel.select()
        self.mapModel.insertRow(0)
        self.mapModel.setData(self.mapModel.index(0, 0), QVariant("-"))
        self.mapModel.setData(self.mapModel.index(0, 1), QVariant(""))
        self.mapModel.setData(self.mapModel.index(0, 2), QVariant(""))
        self.mapModel.setData(self.mapModel.index(0, 3), QVariant(""))
        self.map_cmb.setModel(self.mapModel)
        self.map_cmb.setModelColumn(2)
        self.map_cmb.setCurrentIndex(0)
        
        self.cashModel = QSqlTableModel(self)
        self.cashModel.setTable("master_cash_flow")
        self.cashModel.setEditStrategy(QSqlTableModel.OnManualSubmit)
        self.cashModel.select()
        self.cashModel.insertRow(0)
        self.cashModel.setData(self.cashModel.index(0, 0), QVariant("-"))
        self.cashModel.setData(self.cashModel.index(0, 1), QVariant(""))
        self.cashModel.setData(self.cashModel.index(0, 2), QVariant(""))
        self.cash_cmb.setModel(self.cashModel)
        self.cash_cmb.setModelColumn(2)
        self.cash_cmb.setCurrentIndex(0)
        
        self.dataTipe = {"A":"Aktiva", "K":"Kewajiban", "M":"Modal", "P":"Pendapatan", "B":"Biaya", "L":"Lain (Pendapatan/Biaya)"}
        
        self.initData()
        
  @pyqtSignature("")
  def on_save_pb_clicked(self):
      if self.tipe == "add":
          if self.tambahData():
              self.close()
          else:
              QMessageBox.warning(self, "Chart Of Account","Can not add new data.")
      else:
          if self.updateData():
              self.close()
          else:
              QMessageBox.warning(self, "Chart Of Account","Can not update data")
      
  @pyqtSignature("")
  def on_cancel_pb_clicked(self):
      self.close()

  def tambahData(self):
      if not self.validasi():
          return
      self.mastModel.select()      
      QSqlDatabase.database().transaction()
      if not self.mastModel.insertRow(0):
          return
      self.mastModel.setData(self.mastModel.index(0, 0), QVariant(self.type_cmb.currentText().left(1)))
      self.mastModel.setData(self.mastModel.index(0, 1), QVariant(self.acc_le.text()))
      self.mastModel.setData(self.mastModel.index(0, 2), QVariant(self.desc_le.text()))
      det = "N"
      if self.detail_cb.checkState() == Qt.Checked:
          det = "Y"
      self.mastModel.setData(self.mastModel.index(0, 3), QVariant(det))
      self.mastModel.setData(self.mastModel.index(0, 4), QVariant(self.up_le.text()))
      brs = self.map_cmb.currentIndex()
      map = self.mapModel.data(self.mapModel.index(brs, 0)).toString()
      self.mastModel.setData(self.mastModel.index(0, 6), QVariant(map))
      brs = self.cash_cmb.currentIndex()
      cf = self.cashModel.data(self.cashModel.index(brs, 0)).toString()
      self.mastModel.setData(self.mastModel.index(0, 7), QVariant(cf))
      if not self.mastModel.submitAll():
          return
      if not QSqlDatabase.database().commit():
          return
      return True

  def updateData(self):
      if not self.validasi():          
          return
      self.mastModel.setFilter("kode_perkiraan = '"+self.tipe+"'")
      self.mastModel.select()      
      QSqlDatabase.database().transaction()
      self.mastModel.setData(self.mastModel.index(0, 0), QVariant(self.type_cmb.currentText().left(1)))
      self.mastModel.setData(self.mastModel.index(0, 1), QVariant(self.acc_le.text()))
      self.mastModel.setData(self.mastModel.index(0, 2), QVariant(self.desc_le.text()))
      det = "N"
      if self.detail_cb.checkState() == Qt.Checked:
          det = "Y"
      self.mastModel.setData(self.mastModel.index(0, 3), QVariant(det))
      self.mastModel.setData(self.mastModel.index(0, 4), QVariant(self.up_le.text()))
      brs = self.map_cmb.currentIndex()
      map = self.mapModel.data(self.mapModel.index(brs, 0)).toString()
      self.mastModel.setData(self.mastModel.index(0, 6), QVariant(map))
      brs = self.cash_cmb.currentIndex()
      cf = self.cashModel.data(self.cashModel.index(brs, 0)).toString()
      self.mastModel.setData(self.mastModel.index(0, 7), QVariant(cf))
      if not self.mastModel.submitAll():
          return
      if not QSqlDatabase.database().commit():
          return
      return True

  def initData(self):
      if self.tipe != "add":
          query = QSqlQuery(self.db)
          qStr = "select tipe, kode_perkiraan, nama, detail, up_level, level, map, cf from master_kode_perkiraan where kode_perkiraan = '"+self.tipe+"'"
          query.exec_(qStr)
          query.next()
          tipe = self.dataTipe[unicode(query.value(0).toString())]
          idx = self.type_cmb.findText(tipe, Qt.MatchExactly)
          self.type_cmb.setCurrentIndex(idx)
          
          self.acc_le.setText(unicode(query.value(1).toString()))
          self.desc_le.setText(unicode(query.value(2).toString()))
          
          if query.value(3).toString() == "Y":
              self.detail_cb.setCheckState(Qt.Checked)
          
          self.up_le.setText(unicode(query.value(4).toString()))
          
          brs = self.cashModel.match(self.cashModel.index(0, 0), 0, query.value(7),1, Qt.MatchWrap )
          if len(brs) != 0:
              self.cash_cmb.setCurrentIndex(brs[0].row())
          else:
              self.cash_cmb.setCurrentIndex(0)
              
          brs = self.mapModel.match(self.mapModel.index(0, 0), 0, query.value(6),1, Qt.MatchWrap )
          if len(brs) != 0:
              self.map_cmb.setCurrentIndex(brs[0].row())
          else:
              self.map_cmb.setCurrentIndex(0)
      
  def validasi(self):
      valid = True
      for lineEdit in self.lineedits:
           if lineEdit.text().isEmpty():
               QMessageBox.warning(self, "Chart Of Account","Please cek mandatory column (Yellow background)")
               return False
      return valid

if __name__ == "__main__":
    import sys
    app = QApplication(sys.argv)
    form = CoaEdit()
    form.show()
    app.exec_()
